#include"network.h"

int main()
{
    //创建套接字
    int token = socket(AF_INET, SOCK_STREAM, 0);
    if(token==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_SOCKET);
    }
    else
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"socket is successful");
    }

    //绑定IP和端口
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));

    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=htonl(INADDR_ANY);
    addr.sin_port=htons(8080);

    int bin = bind(token,(const sockaddr*)&addr,sizeof(addr));
    if(bin==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_BIND);
    }
    else
    {
        log_message(LOG_LEVEL_SUCCESS,__FILE__,__LINE__,"bind is successful");
    }

    //持续监听
    int ls = listen(token,10);
    if(ls==-1)
    {
        log_message(LOG_LEVEL_ERROR,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_LISTEN);
    }
    else
    {
        log_message(LOG_LEVEL_SUCCESS,__FILE__,__LINE__,"listen is successful");
    }

    struct sockaddr_in lock;
    memset(&lock, 0, sizeof(lock));
    socklen_t sz = sizeof(lock);
    //持续接收请求
    int new_token = accept(token,(sockaddr*)&lock,&sz);
    if(new_token==-1)
    {
        log_message(LOG_LEVEL_INFO,__FILE__,__LINE__,"错误码：%d,错误信息：%s",errno,strerror(errno));
        exit(LOG_LEVEL_ACCEPT);
    }

    char buffer[1024]={0};
    while(1)
    {
        //读取信息
        ssize_t t =recv(new_token, buffer, sizeof(buffer)-1, 0);
        if(t>0)
        {
            //打印读取内容
            buffer[t-1]=0;
            std::cout<<"客户端收到请求："<<buffer<<std::endl;
        }
        else if(t==0)
        {
            std::cout<<"对方关闭了连接"<<std::endl;
            break;
        }
    }
    close(token);

    return 0;
}